<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Config, Order, Goods, Ordergoods, Message};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;


class User extends Base
{

    public function getordergoodlist()
    {
        $id = $this->request->get('id/d', 0);
        $result = (new Ordergoods())->order('type asc')->field('id,title,number,type,sjtotal')->where(['del' => 1, 'orderid' => $id])->select() ?? [];
        $this->result($result, 0, '获取成功');
    }

    public function getdatas()
    {
        $type = $this->request->get('type/d', 0);
        $times = $this->request->get('times/s', '');
        $times = explode(' ~ ', $times);
        $start = $times[0]  ??  date('Y-m-d');
        $end = $times[1]  ??  date('Y-m-d');
        //获取原材料
        $goods = (new Goods())->where(['type' => [1, 2]])->where('groups', $type)->where('del', 1)->select();
        $zpgoods = (new Goods())->where(['type' => [3]])->where('del', 1)->select();
        $result = [
            'chuku' => [], //出库占比
            'ruku' => [],
            'cgtotal' => [
                'total' => 0,
                'wuliao' => 0,
                'shouyin' => 0,
                'wuliaoing' => 0,
                'shouyining' => 0
            ],
            'wuliaolist' => [],
            'zengpin' => [
                'total' => (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [6], 'del' => 1, 'status' => [1, 2]])->sum('total'), //采购额
                'zplist' => []
            ],
        ];
        $groups = config()["config"]['type']; //品牌列表
        foreach ($zpgoods as $zgoods) {
            $list = [];
            foreach ($groups as $k => $group) {
                //查询时间内出库订单
                $corderids = (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [1, 2, 3], 'groups' => $k, 'del' => 1, 'status' => [1, 2]])->column('id') ?? [];
                //查询时间段内出库订单
                $ordergoods = (new Ordergoods())->field('number,sjtotal')->where(['orderid' => $corderids, 'del' => 1, 'goodsid' => $zgoods['id']])->select();
                $number = 0;
                $sjtotal = 0;
                foreach ($ordergoods as $ogoods) {
                    $number += $ogoods['number'];
                    $sjtotal += $ogoods['number'] * $ogoods['sjtotal'];
                }
                $list[] = [
                    'pinpai' => $group, //品牌名称
                    'number' => $number, //使用件数
                    'total' => $sjtotal, //价值总额
                ];
            }
            $jhorder = (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [6], 'del' => 1, 'status' => [1, 2]])->column('id') ?? [];
            $jhnumber = (new Ordergoods())->where(['orderid' => $jhorder, 'del' => 1, 'goodsid' => $zgoods['id']])->sum('number');
            $result['zengpin']['zplist'][] = [
                'name' => $zgoods['title'] ?? '', //名称
                'number' => $jhnumber, //进货数量
                'list' => $list
            ];
        }
        //查询时间内出库订单
        $corderids = (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [1, 2, 3], 'groups' => $type, 'del' => 1, 'status' => [1, 2]])->column('id') ?? [];
        //查询时间内入库订单
        $rorderids = (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [4, 5], 'groups' => $type, 'del' => 1, 'status' => [1, 2]])->column('id') ?? [];
        //正在出库订单
        $callorderids = (new Order())->where(['type' => [1, 2, 3], 'groups' => $type, 'del' => 1, 'status' => [1]])->column('id') ?? [];
        //正在入库订单
        $rallorderids = (new Order())->where(['type' => [4, 5], 'groups' => $type, 'del' => 1, 'status' => [1]])->column('id') ?? [];
        $result['cgtotal'] = [
            'total' => 0,
            'wuliao' => (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [4], 'groups' => $type, 'del' => 1, 'status' => [1, 2]])->sum('total'),
            'shouyin' => (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [5], 'groups' => $type, 'del' => 1, 'status' => [1, 2]])->sum('total'),
            'wuliaoing' => (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [4], 'groups' => $type, 'del' => 1, 'status' => [1]])->sum('total'),
            'shouyining' => (new Order())->whereBetween('nowtime', [$start, $end])->where(['type' => [5], 'groups' => $type, 'del' => 1, 'status' => [1]])->sum('total')
        ];
        $result['cgtotal']['total'] = $result['cgtotal']['wuliao'] + $result['cgtotal']['shouyin'];
        foreach ($goods as $good) {
            //出库查询
            $number = (new Ordergoods())->where(['orderid' => $corderids, 'del' => 1, 'goodsid' => $good['id']])->sum('number');
            if ($number > 0) {
                $result['chuku'][] = [
                    'name' => $good['title'] ?? '',
                    'value' => $number,
                    'labelText' => $good['title'] . $number . '件'
                ];
            }
            $number1 = (new Ordergoods())->where(['orderid' => $rorderids, 'del' => 1, 'goodsid' => $good['id']])->sum('number');
            if ($number1 > 0) {
                $result['ruku'][] = [
                    'name' => $good['title'] ?? '',
                    'value' => $number1,
                    'labelText' => $good['title'] . $number1 . '件'
                ];
            }
            $result['wuliaolist'][] = [
                'title' => $good['title'] ?? '', //名称
                'sku' =>  $good['sku'] ?? 0, //库存
                'ruku' => (new Ordergoods())->where(['orderid' => $rallorderids, 'del' => 1, 'goodsid' => $good['id']])->sum('number'),
                'chuku' => (new Ordergoods())->where(['orderid' => $callorderids, 'del' => 1, 'goodsid' => $good['id']])->sum('number'),
                'rukutime' =>  $number1 ?? 0, //查询时间内出库
                'chukutime' =>  $number ?? 0, //查询时间内入库
            ];
        }
        if (count($result['chuku']) <= 0) {
            $result['chuku'][] = [
                'name' => '暂无数据',
                'value' => 0
            ];
        }
        if (count($result['ruku']) <= 0) {
            $result['ruku'][] = [
                'name' => '暂无数据',
                'value' => 0
            ];
        }
        $this->result($result, 0, '获取成功');
    }

    //确认订单
    public function fahuopost()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'fahuoremark' => 'require',
        ], [
            'id.require' => 'id不能为空',
            'fahuoremark.require' => '备注必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查找订单
        $ordergoods = (new Ordergoods())->where('id', $data['id'])->find();
        if (empty($ordergoods)) {
            $this->result([], 1, '数据不存在');
        }
        if ($ordergoods['isfahuo'] == 2) {
            $this->result([], 1, '已提交过发货信息，无需重复提交');
        }
        if ($this->request->user['type'] == 3 && $ordergoods['fhr'] != 2) {
            $this->result([], 1, '无发货操作权限');
        }
        if ($this->request->user['type'] == 4 && $ordergoods['fhr'] != 1) {
            $this->result([], 1, '无发货操作权限');
        }
        //查询order
        $order = (new Order())->where('id', $ordergoods['orderid'])->find();
        if (empty($order) || $order['status'] != 1) {
            $this->result([], 1, '关联订单不存在或处于非进行中状态');
        }
        if ($this->request->user['type'] == 3 && $order['fconfirm'] != 1) {
            $this->result([], 1, '财务已确认，无需进行单独发货操作');
        }
        if ($this->request->user['type'] == 4 && $order['wconfirm'] != 1) {
            $this->result([], 1, '仓库已确认，无需进行单独发货操作');
        }
        Db::startTrans();
        try {
            (new Ordergoods())->where('id', $data['id'])->update(['isfahuo' => 2, 'remark' => $data['fahuoremark']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '操作成功');
    }

    //确认订单
    public function confirmorder()
    {
        $id = $this->request->post('id/d', 0);
        $type = $this->request->post('type/s', '');
        if (empty($type)) {
            $this->result([], 1, '确认类型不能为空');
        }
        $order = (new Order())->where(['del' => 1, 'id' => $id])->find();
        if (empty($order) || $order['status'] != 1) {
            $this->result([], 1, '订单不存在或不处于进行中状态');
        }
        $confirm = (new Order())->getconfirms($order, $this->request->user['type']);
        if ($confirm != $type) {
            $this->result([], 1, '当前状态不正确，请刷新重试');
        }
        $data = $this->request->post();
        $update = [];
        $update[$type] = 2;
        if ($confirm == 'wconfirm') {
            if (empty($data['wlname'])) {
                $this->result([], 1, '请填写物流名称');
            }
            if (empty($data['wlnumber'])) {
                $this->result([], 1, '请填写物流单号');
            }
            if (empty($data['fileList']) || count($data['fileList']) <= 1) {
                $this->result([], 1, '请上传物流图片');
            }
            $update['wlname'] = $data['wlname'];
            $update['wlnumber'] = $data['wlnumber'];
            $update['wlimages'] = json_encode($data['fileList'], true);
        }
        $messages = '';
        switch ($order['type']) {
            case '1':
                //首次确认通知售后
                if ($confirm == 'mconfirm' && $order['afconfirm'] == 1) {
                    $messages = 'afconfirm';
                }
                //二次确认通知仓库和财务
                if ($confirm == 'mconfirm' && $order['afconfirm'] == 2) {
                    $messages = 'wconfirm,fconfirm';
                }
                //售后确认通知仓库
                if ($confirm == 'afconfirm') {
                    $messages = 'wconfirm';
                }
                //仓库确认通知售后
                if ($confirm == 'wconfirm') {
                    $messages = 'afconfirm';
                }
                //财务确认通知售后
                if ($confirm == 'fconfirm') {
                    $messages = 'afconfirm';
                }
                break;
            case '2':
                //确认通知仓库
                if ($confirm == 'mconfirm') {
                    $messages = 'wconfirm,fconfirm';
                }
                //仓库确认通知财务
                if ($confirm == 'wconfirm') {
                    $messages = 'afconfirm';
                }
                //财务确认通知售后
                if ($confirm == 'fconfirm') {
                    $messages = 'afconfirm';
                }
                break;
            case '3':
                //确认通知仓库
                if ($confirm == 'mconfirm') {
                    $messages = 'wconfirm,fconfirm';
                }
                //仓库确认通知售后
                if ($confirm == 'wconfirm') {
                    $messages = 'afconfirm';
                }
                //财务确认通知售后
                if ($confirm == 'fconfirm') {
                    $messages = 'afconfirm';
                }
                break;
            case '4':
                //确认通知仓库
                if ($confirm == 'mconfirm') {
                    $messages = 'wconfirm';
                }
                // if ($confirm == 'wconfirm') {
                //     $messages = 'fconfirm';
                // }
                break;
            case '5':
                //确认通知仓库
                if ($confirm == 'mconfirm') {
                    $messages = 'wconfirm';
                }
                // if ($confirm == 'wconfirm') {
                //     $messages = 'fconfirm';
                // }
                break;
            case '6':
                //确认通知仓库
                if ($confirm == 'swconfirm') {
                    $messages = 'wconfirm';
                }
                // if ($confirm == 'wconfirm') {
                //     $messages = 'fconfirm';
                // }
                break;
            default:
                # code...
                break;
        }
        Db::startTrans();
        try {
            (new Order())->where('id', $order['id'])->update($update);
            //检测是否完成
            (new Order())->finishs($order['id']);
            if (!empty($messages)) {
                if (empty($order['groups'])) {
                    $order['groups'] = 99;
                }
                $messages = explode(',', $messages);
                if (count($messages) > 0) {
                    foreach ($messages as $k => $messagea) {
                        (new Message())->allowfield(true)->save([
                            'orderid' => $order['id'],
                            'user_id' => $this->request->user_id,
                            'type' => $order['type'],
                            'groups' => $order['groups'] ?? 99,
                            'text' => $this->request->user['account'] . '确认了任务信息',
                            $messagea => 1
                        ]);
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '操作成功');
    }

    //取消订单
    public function cacelorder()
    {
        $id = $this->request->post('id/d', 0);
        $order = (new Order())->where(['del' => 1, 'id' => $id, 'status' => 1])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或已完成、取消');
        }
        if ($order['user_id'] != $this->request->user_id) {
            $this->result([], 1, '非发布人无操作权限');
        }
        $res = (new Order())->where('id', $id)->update(['status' => 3]);
        if ($res) {
            if ($order['groups'] == 0) {
                $order['groups'] = 99;
            }
            if ($order['type'] == 6) {
                (new Message())->allowfield(true)->save([
                    'orderid' => $order['id'],
                    'user_id' => $this->request->user_id,
                    'type' => $order['type'],
                    'groups' => $order['groups'] ?? 99,
                    'text' => $this->request->user['account'] . '取消了任务信息',
                    'swconfirm' => 1
                ]);
            } else {
                (new Message())->allowfield(true)->save([
                    'orderid' => $order['id'],
                    'user_id' => $this->request->user_id,
                    'type' => $order['type'],
                    'groups' => $order['groups'] ?? 99,
                    'text' => $this->request->user['account'] . '取消了任务信息',
                    'mconfirm' => 1
                ]);
            }

            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    public function myorderlist()
    {
        $data = $this->request->get();
        $page = $data['page'] ?? 1;
        $page = (int)$page;
        $where = [];
        $where[] = ['user_id', '=', $this->request->user_id];
        if (!empty($data['id'])) {
            $where[] = ['id', '=', $data['id']];
        }
        if (!empty($data['keywords'])) {
            $where[] = ['ordersn|name|mobile|area|remark|kxremark|qyremark|kremark|nowtime', 'like', '%' . $data['keywords'] . '%'];
        }
        switch ($data['status']) {
            case '0':
                # code...
                break;
            case '2':
                $where[] = ['status', '=', 1];
                break;
            case '3':
                $where[] = ['status', '=', 2];
                break;
            case '4':
                $where[] = ['status', '=', 3];
                break;
            default:
                $this->result([], 1, '状态错误');
                break;
        }
        $sorts = ['nowtime' => 'desc', 'created' => 'desc'];
        $result = (new Order())->limit(10)
            ->page($page)->order($sorts)
            ->whereOr(function ($query) use ($where) {
                $query->where($where);
            })->select();
        foreach ($result as $row) {
            $row['editdel'] = 1; //1表示不可编辑 2表示可编辑和取消
            if (($row['type'] == 1 || $row['type'] == 2 || $row['type'] == 3 || $row['type'] == 4 || $row['type'] == 5) && $row['mconfirm'] == 1 && $row['status'] == 1 && $row['del'] == 1) {
                $row['editdel'] = 2;
            }
            if ($row['type'] == 6 && $row['swconfirm'] == 1 && $row['status'] == 1 && $row['del'] == 1) {
                $row['editdel'] = 2;
            }
            if ($row['suid'] > 0) {
                $row['uidname'] = (new Users())->where('id', $row['suid'])->value('account');
            }
            $row['images'] = json_decode($row['images'], true) ?? [];
            $row['total'] = (float)$row['total'];
            $row['user_name'] = (new Users())->where('id', $row['user_id'])->value('account') ?? '';
            $row['groups_name'] =  config()["config"]['type_name'][$row['groups']] ?? '';
            $row['ordertype'] =  config()["config"]['ordertype'][$row['type']] ?? '';
            $row['kxtype_name'] =  config()["config"]['kxtype'][$row['kxtype']] ?? '';
            $row['qytype_name'] =  config()["config"]['qytype'][$row['qytype']] ?? '';
            $row['kstype_name'] =  config()["config"]['kstype'][$row['kstype']] ?? '';
            $row['ystype_name'] =  config()["config"]['ystype'][$row['ystype']] ?? '';
            $row['dptype_name'] =  config()["config"]['dptype'][$row['dptype']] ?? '';
            $row['goods'] = [];
            $row['goods'] = (new Ordergoods())->order('type asc')->field('id,title,number,type,sjtotal')->where(['del' => 1, 'orderid' => $row['id']])->select() ?? [];
            $row['topuser'] = [];
            if ($row['topid'] > 0) {
                $topuser = (new Order())->where('id', $row['topid'])->find() ?? [];
                if (!empty($topuser)) {
                    $topuser['images'] = json_decode($topuser['images'], true) ?? [];
                    $topuser['areas'] = (float)$topuser['areas'];
                    $topuser['groups_name'] =  config()["config"]['type_name'][$topuser['groups']] ?? '';
                    $topuser['ordertype'] =  config()["config"]['ordertype'][$topuser['type']] ?? '';
                    $topuser['kxtype_name'] =  config()["config"]['kxtype'][$topuser['kxtype']] ?? '';
                    $topuser['qytype_name'] =  config()["config"]['qytype'][$topuser['qytype']] ?? '';
                    $topuser['kstype_name'] =  config()["config"]['kstype'][$topuser['kstype']] ?? '';
                    $topuser['ystype_name'] =  config()["config"]['ystype'][$topuser['ystype']] ?? '';
                    $topuser['dptype_name'] =  config()["config"]['dptype'][$topuser['dptype']] ?? '';
                }
                $row['topuser'] = $topuser;
            }
            //状态文本判断
            $row['status_text'] = $row->StatusText;
        }
        $this->result(['data' => $result], 0, '获取成功');
    }

    public function orderlist()
    {
        $data = $this->request->get();
        $page = $data['page'] ?? 1;
        $page = (int)$page;
        $where = [];
        $where1 = [];
        //分组权限判别
        if ($this->request->user['groups'] != 99) {
            $groups = explode(',', $this->request->user['groups']) ?? [];
            $groups = array_unique($groups);
            $groups = array_filter($groups);
            if ($this->request->user['type'] == 5 || $this->request->user['type'] == 4 || $this->request->user['type'] == 10) {
                $groups[] = 0;
            }
            $where[] = ['groups', 'in', $groups];
        }
        if (!empty($data['keywords'])) {
            $where[] = ['nowtime|ordersn|name|mobile|area|remark|kxremark|qyremark|kremark|nowtime', 'like', '%' . $data['keywords'] . '%'];
        }
        //只显示自己的和自己权限的订单
        switch ($data['status']) {
            case '0':
                $where[] = ['status', 'in', [1, 2]];

                break;
            case '1':
                $where[] = ['status', '=', 1];
                break;
            case '2':
                $where[] = ['status', '=', 1];
                break;
            case '3':
                $where[] = ['status', '=', 2];
                break;
            case '4':
                $where[] = ['status', '=', 3];
                break;
            default:
                $this->result([], 1, '状态错误');
                break;
        }
        $where1 = $where;
        //显示自己发布的单
        $where[] = ['user_id', '=', $this->request->user_id];
        //显示自己权限内的订单
        switch ($this->request->user['type']) {
                //业务经理
            case '1':
                $where1[] = ['user_id', '=', $this->request->user_id];
                break;
                //售后经理
            case '2':
                $where1[] = ['suid', '=', $this->request->user_id];
                break;
                //财务
            case '3':
                $where1[] = ['type', 'in', [1, 2, 3, 4, 5]];
                break;
            case '4':
                //仓库
                $where1[] = ['type', 'in', [1, 2, 3, 4, 5, 6]];
                break;
            case '5':
                //采购
                $where1[] = ['user_id', '=', $this->request->user_id];
                break;
            case '9':
                //仓库财务
                $where1[] = ['type', 'in', [1, 2, 3, 4, 5]];
                break;
            case '10':
                $where1[] = ['type', 'in', [1, 2, 3, 4, 5, 6]];
                //主管
                break;
            default:
                $this->result([], 1, '权限错误');
                break;
        }
        $sorts = ['updated' => 'desc', 'nowtime' => 'desc'];
        $result = (new Order())->limit(10)
            ->page($page)->order($sorts)
            ->whereOr(function ($query) use ($where) {
                $query->where($where);
            })->whereOr(function ($query) use ($where1) {
                $query->where($where1);
            })->select();
        foreach ($result as $k => $row) {
            $row['images'] = json_decode($row['images'], true) ?? [];
            $row['wlimages'] = json_decode($row['wlimages'], true) ?? [];
            //确认按钮显示
            $row['confirm'] = (new Order())->getconfirms($row, $this->request->user['type']);
            if ($data['status'] == 1 && empty($row['confirm'])) {
                unset($result[$k]);
                continue;
            }
            //取消和编辑按钮显示
            $row['editdel'] = 1;
            //标记录入人按钮
            $row['editdel2'] = 1;
            //售后经理编辑
            if ($this->request->user['type'] == 2 && $row['status'] == 1 && ($row['type'] == 1 || $row['type'] == 2 || $row['type'] == 3) && $row['mconfirm'] == 2 && $row['afconfirm'] == 1) {
                $row['editdel'] = 2;
            }
            if ($this->request->user['type'] == 2 && $row['status'] == 1 && ($row['type'] == 1 || $row['type'] == 2 || $row['type'] == 3) && $row['fconfirm'] == 1 && $row['wconfirm'] == 1) {
                $row['editdel2'] = 2;
            }
            if ($row['suid'] > 0) {
                $row['uidname'] = (new Users())->where('id', $row['suid'])->value('account');
            }
            $row['total'] = (float)$row['total'];
            $row['areas'] = (float)$row['areas'];
            $row['user_name'] = (new Users())->where('id', $row['user_id'])->value('account') ?? '';
            $row['groups_name'] =  config()["config"]['type'][$row['groups']] ?? '';
            $row['ordertype'] =  config()["config"]['ordertype'][$row['type']] ?? '';
            $row['kxtype_name'] =  config()["config"]['kxtype'][$row['kxtype']] ?? '';
            $row['qytype_name'] =  config()["config"]['qytype'][$row['qytype']] ?? '';
            $row['kstype_name'] =  config()["config"]['kstype'][$row['kstype']] ?? '';
            $row['ystype_name'] =  config()["config"]['ystype'][$row['ystype']] ?? '';
            $row['dptype_name'] =  config()["config"]['dptype'][$row['dptype']] ?? '';
            $row['goods'] = [];
            $ordergoods = (new Ordergoods())->order(['fhr' => 'desc', 'type' => 'asc'])->field('id,title,number,type,sjtotal,goodsid,fhr,isfahuo,remark')->where(['del' => 1, 'orderid' => $row['id']])->select() ?? [];
            foreach ($ordergoods as $k => $v) {
                //财务显示标签
                $ordergoods[$k]['isshow'] = 0; //0什么都不显示 1编辑 2查看
                if ($row['type'] <= 3) {
                    if ($this->request->user['type'] == 3 && $v['fhr'] == 2) {
                        if ($v['isfahuo'] == 2) {
                            $ordergoods[$k]['isshow'] = 2;
                        } elseif ($v['isfahuo'] == 1 && $row['fconfirm'] == 1) {
                            $ordergoods[$k]['isshow'] = 1;
                        }
                    } elseif ($this->request->user['type'] == 4 && $v['fhr'] == 1) {
                        if ($v['isfahuo'] == 2) {
                            $ordergoods[$k]['isshow'] = 2;
                        } elseif ($v['isfahuo'] == 1 && $row['wconfirm'] == 1) {
                            $ordergoods[$k]['isshow'] = 1;
                        }
                    }
                }
                if ($row['type'] <= 3) {
                    $ordergoods[$k]['fh_status'] = '待发货';
                    if ($row['fconfirm'] == 1 && $v['fhr'] == 2) {
                        if ($v['isfahuo'] == 2) {
                            $ordergoods[$k]['fh_status'] = '已发货';
                        }
                    } elseif ($row['fconfirm'] == 2 && $v['fhr'] == 2) {
                        $ordergoods[$k]['fh_status'] = '已确认';
                    } elseif ($row['wconfirm'] == 1 && $v['fhr'] == 1) {
                        if ($v['isfahuo'] == 2) {
                            $ordergoods[$k]['fh_status'] = '已发货';
                        }
                    } elseif ($row['wconfirm'] == 2 && $v['fhr'] == 1) {
                        $ordergoods[$k]['fh_status'] = '已确认';
                    } else {
                        $ordergoods[$k]['fh_status'] = '';
                    }
                }
                if ($row['type']) {
                    $goods = (new Goods())->where('id', $v['goodsid'])->find();
                    $ordergoods[$k]['red'] = 2;
                    if (!empty($goods)) {
                        if ($row['dptype'] == 1 && $v['number'] == $goods['default_num']) {
                            $ordergoods[$k]['red'] = 1;
                        }
                        if ($row['dptype'] == 2 && $v['number'] == $goods['default_num2']) {
                            $ordergoods[$k]['red'] = 1;
                        }
                        if ($row['dptype'] == 3 && $v['number'] == $goods['default_num3']) {
                            $ordergoods[$k]['red'] = 1;
                        }
                    }
                }
            }
            $row['goods'] = $ordergoods;
            $row['topuser'] = [];
            if ($row['topid'] > 0) {
                $topuser = (new Order())->where('id', $row['topid'])->find() ?? [];
                if (!empty($topuser)) {
                    $topuser['images'] = json_decode($topuser['images'], true) ?? [];
                    $topuser['areas'] = (float)$topuser['areas'];
                    $topuser['groups_name'] =  config()["config"]['type_name'][$topuser['groups']] ?? '';
                    $topuser['ordertype'] =  config()["config"]['ordertype'][$topuser['type']] ?? '';
                    $topuser['kxtype_name'] =  config()["config"]['kxtype'][$topuser['kxtype']] ?? '';
                    $topuser['qytype_name'] =  config()["config"]['qytype'][$topuser['qytype']] ?? '';
                    $topuser['kstype_name'] =  config()["config"]['kstype'][$topuser['kstype']] ?? '';
                    $topuser['ystype_name'] =  config()["config"]['ystype'][$topuser['ystype']] ?? '';
                    $topuser['dptype_name'] =  config()["config"]['dptype'][$topuser['dptype']] ?? '';
                }
                $row['topuser'] = $topuser;
            }
            //状态文本判断
            $row['status_text'] = $row->StatusText;
        }
        if (in_array($this->request->user['type'], [2, 3, 4, 9, 10])) {
            $scrollList = [
                ['id' => 0, 'name' =>  '全部'],
                ['id' => 1, 'name' =>  '待确认'],
                ['id' => 2, 'name' => '进行中'],
                ['id' => 3, 'name' => '已完成'],
                ['id' => 4, 'name' => '已取消']
            ];
        } else {
            $scrollList = [
                ['id' => 0, 'name' =>  '全部'],
                ['id' => 2, 'name' => '进行中'],
                ['id' => 3, 'name' => '已完成'],
                ['id' => 4, 'name' => '已取消']
            ];
        }
        $result = array_values($result->toArray());
        $this->result(['data' => $result, 'scrollList' => $scrollList], 0, '获取成功');
    }

    public function getgoods()
    {
        $groups = $this->request->get('groups/d', 0);
        $type = $this->request->get('type'); //0全部  1物料 2收银机 3赠品
        $result = (new Goods())->field('title,id,type,groups,sku,default_num,default_num2,default_num3')->where(['groups' => $groups]);
        if (!empty($type)) {
            $type = explode(',', $type);
            $mygroups = explode(',', $this->request->user['groups']);
            if (!empty($type[0]) && $type[0] == 3 && $this->request->user['groups'] != 99 && count($mygroups) <= 1) {
                if (in_array($mygroups[0], [7, 8])) {
                    $result = $result->where(['type' => $type, 'del' => 1, 'cangku' => 2]);
                } else {
                    $result = $result->where(['type' => $type, 'del' => 1, 'cangku' => 1]);
                }
            } else {
                $result = $result->where(['type' => $type, 'del' => 1]);
            }
        } else {
            $result = $result->where(['type' => -1, 'del' => 1]);
        }
        $result = $result->select();
        $this->result($result, 0, '获取成功');
    }

    public function delordergoods()
    {
        $id = $this->request->post('id/d', 0);
        $orderid = $this->request->post('orderid/d', 0);
        $ogoods = (new Ordergoods())
            ->where(['orderid' => $orderid, 'id' => $id])
            ->find();
        if (empty($ogoods)) {
            $this->result([], 1, '信息不存在，请刷新页面重试');
        }
        //订单完成不可删除
        $order = (new Order())->where(['id' => $ogoods['orderid'], 'del' => 1, 'status' => 1])->find();
        if (empty($order)) {
            $this->result([], 1, '订单完成或不存在，商品不可继续删除');
        }
        $res = (new Ordergoods())->where('id', $id)->update(['del' => 2]);
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function editfhrs()
    {
        $id = $this->request->post('id/d', 0);
        $orderid = $this->request->post('orderid/d', 0);
        $fhr = $this->request->post('status/d', 1);
        if ($fhr != 1 && $fhr != 2) {
            $this->result([], 1, '发货人类型错误');
        }
        $ogoods = (new Ordergoods())
            ->where(['orderid' => $orderid, 'id' => $id])
            ->find();
        if (empty($ogoods)) {
            $this->result([], 1, '信息不存在，请刷新页面重试');
        }
        if ($ogoods['isfahuo'] == 2) {
            $this->result([], 1, '已经发货，不可继续变更');
        }
        //订单完成不可删除
        $order = (new Order())->where(['id' => $ogoods['orderid'], 'del' => 1, 'status' => 1])->find();
        if (empty($order)) {
            $this->result([], 1, '订单完成或不存在，商品不可继续删除');
        }
        if ($order['wconfirm'] != 1 || $order['fconfirm'] != 1) {
            $this->result([], 1, '财务或仓库已确认，不可重复标记');
        }
        if ($order['type'] > 3) {
            $this->result([], 1, '订单类型不可标记');
        }
        $res = (new Ordergoods())->where('id', $id)->update(['fhr' => $fhr]);
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function dockorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['type'])) {
                $this->result([], 1, '提交类型不能为空');
            }
            //权限判断
            switch ($this->request->user['type']) {
                case '1':
                    if ($data['type'] != 1) {
                        $this->result([], 1, '无操作权限');
                    }
                    break;
                case '2':
                    if ($data['type'] != 1 && $data['type'] != 2 && $data['type'] != 3) {
                        $this->result([], 1, '无操作权限');
                    }
                    if (empty($data['id']) && $data['type'] == 1) {
                        $this->result([], 1, '无发布权限');
                    }
                    break;
                case '3':
                    if ($data['type'] != 4 && $data['type'] != 5) {
                        $this->result([], 1, '无操作权限');
                    }
                    break;
                case '5':
                    if ($data['type'] != 6) {
                        $this->result([], 1, '无操作权限');
                    }
                    break;
                default:
                    $this->result([], 1, '无操作权限');
                    break;
            }
            //权限判断结束
            if (empty($data['id'])) {
                $data['ordersn'] = date('YmdHis') . mt_rand(10000, 99999);
            }
            switch ($data['type']) {
                    //交接单发布
                case '1':
                    $validate = new Validate([
                        'nowtime' => 'require',
                        'suid' => 'require',
                        'groups' => 'require|gt:0',
                        'name' => 'require',
                        'mobile' => 'require',
                        'level' => 'require',
                        'area' => 'require',
                        'cost' => 'require',
                        'remark' => 'require',
                        'kxremark' => 'require',
                        'qyremark' => 'require',
                        'kremark' => 'require',
                        'kstype' => 'require',
                        'ystype' => 'require',
                        'dptype' => 'require',
                        'kxtype' => 'require',
                        'qytype' => 'require',
                        'areas' =>  'require|gt:0|float',
                        'images' => 'require',
                    ], [
                        'suid.require' => '售后经理不能为空',
                        'nowtime.require' => '发布时间必须填写',
                        'groups.require' => '组别不能为空',
                        'groups.gt' => '组别必须选择',
                        'mobile.require' => '联系电话不能为空',
                        'level.require' => '签约级别不能为空',
                        'name.require' => '联系人不能为空',
                        'area.require' => '签约区域不能为空',
                        'cost.require' => '签约费用不能为空',
                        'remark.require' => '备注/说明不能为空',
                        'kxremark.require' => '款项信息说明不能为空',
                        'qyremark.require' => '签约级别是否正常信息说明不能为空',
                        'kremark.require' => '重点备注不能为空',
                        'kstype.require' => '货架款式不能为空',
                        'ystype.require' => '货架颜色不能为空',
                        'dptype.require' => '店铺类型不能为空',
                        'kxtype.require' => '款项类型不能为空',
                        'qytype.require' => '是否按照签约级别正常配送不能为空',
                        'areas.require' => '店铺面积不能为空',
                        'areas.gt' => '店铺面积必须大于0',
                        'areas.float' => '店铺面积必须是数字',
                        'images.require' => '合同照片不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    if (mb_substr($data['name'], -1, 1, 'utf-8') == '总') {
                        $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总等泛词');
                    }
                    if (strpos($data['name'], '总监') > 0 || strpos($data['name'], '先生') > 0 || strpos($data['name'], '美女') > 0 || strpos($data['name'], '女士') > 0 || strpos($data['name'], '老板') > 0 || strpos($data['name'], '小姐') > 0) {
                        $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总、总监等泛词');
                    }
                    if (count($data['images']) < 2) {
                        $this->result([], 1, '合同照片不能低于俩张');
                    }
                    $data['images'] = json_encode($data['images'], true);
                    $model = new Order();
                    //查询手机号码对应是否已添加
                    $jjhave = $model->where(['type' => $data['type'], 'groups' => $data['groups'], 'mobile' => $data['mobile'], 'status' => [1, 2]])->find();
                    if (empty($data['id']) && !empty($jjhave)) {
                        $this->result([], 1, '当前分组此手机号原对应用户' . $jjhave['name'] . '已添加');
                    }
                    if (!empty($data['id']) && !empty($jjhave) && $jjhave['id'] != $data['id']) {
                        $this->result([], 1, '当前分组此手机号原对应用户' . $jjhave['name'] . '已添加');
                    }
                    if (!empty($data['id'])) {
                        $order = $model->where(['id' => $data['id'], 'del' => 1])->find();
                        if (empty($order)) {
                            $this->result([], 1, '任务单不存在或取消');
                        }
                        if (empty($data['confirm']) && $order['mconfirm'] != 1) {
                            $this->result([], 1, '管理已确认,任务不可编辑');
                        }
                    }
                    $save = [];
                    $update = [];
                    $data['alllist'] = [];
                    $data['wllist'] = $data['wllist'] ?? [];
                    $data['zplist'] = $data['zplist'] ?? [];
                    $data['alllist'] = array_merge($data['wllist'], $data['zplist']);
                    if (count($data['alllist']) < 1) {
                        $this->result([], 1, '必须选择物料、赠品信息');
                    }
                    $getsandu = $this->getwuliaoarr($data);
                    if (!empty($getsandu['save'])) {
                        $save = $getsandu['save'];
                    }
                    if (!empty($getsandu['update'])) {
                        $update = $getsandu['update'];
                    }
                    Db::startTrans();
                    try {
                        if (!empty($data['id'])) {
                            //售后修改重新需要管理确认
                            if (!empty($data['confirm']) && $data['confirm'] == 'afconfirm') {
                                $data['mconfirm'] = 1; //管理确认
                                $data['afconfirm'] = 2; //售后确认
                                (new Message())->allowfield(true)->save([
                                    'orderid' => $data['id'],
                                    'user_id' => $this->request->user_id,
                                    'type' => $data['type'],
                                    'groups' => $data['groups'] ?? 99,
                                    'text' => $this->request->user['account'] . '编辑了任务信息待确认',
                                    'mconfirm' => 1
                                ]);
                            }
                            $model->allowfield(true)->save($data, ['id' => $data['id']]);
                        } else {
                            $data['user_id'] = $this->request->user_id;
                            $data['mconfirm'] = 1; //管理确认
                            $data['afconfirm'] = 1; //售后确认
                            $data['wconfirm'] = 1; //仓库确认
                            $data['fconfirm'] = 1; //财务确认
                            $data['id'] = $model->strict(false)->insertGetId($data);
                            foreach ($save as $k => $sv) {
                                $save[$k]['orderid'] = $data['id'];
                            }
                            (new Message())->allowfield(true)->save([
                                'orderid' => $data['id'],
                                'user_id' => $this->request->user_id,
                                'type' => $data['type'],
                                'groups' => $data['groups'] ?? 99,
                                'text' => $this->request->user['account'] . '新建了任务待确认',
                                'mconfirm' => 1
                            ]);
                        }
                        if (count($save) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($save);
                        }
                        if (count($update) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($update);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                    //首单发货
                case '2':
                    $validate = new Validate([
                        // 'topid' => 'require|gt:0',
                        'nowtime' => 'require',
                        'groups' => 'require|gt:0',
                        'name' => 'require',
                        'mobile' => 'require',
                        'kremark' => 'require',
                    ], [
                        // 'topid.require' => '关联交接单必须填写',
                        // 'topid.gt' => '关联交接单必须填写',
                        'nowtime.require' => '发布时间必须填写',
                        'groups.require' => '组别不能为空',
                        'groups.gt' => '组别必须选择',
                        'mobile.require' => '联系电话不能为空',
                        'name.require' => '联系人不能为空',
                        'kremark.require' => '重点备注不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    if (mb_substr($data['name'], -1, 1, 'utf-8') == '总') {
                        $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总等泛词');
                    }
                    if (strpos($data['name'], '总监') > 0 || strpos($data['name'], '先生') > 0 || strpos($data['name'], '美女') > 0 || strpos($data['name'], '女士') > 0 || strpos($data['name'], '老板') > 0 || strpos($data['name'], '小姐') > 0) {
                        $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总、总监等泛词');
                    }
                    $model = new Order();
                    //不可变更分组
                    if (!empty($data['id'])) {
                        $order = $model->where(['id' =>  $data['id'], 'type' => $data['type']])->find();
                        if (empty($order)) {
                            $this->result([], 1, '订单不存在');
                        }
                        if ($data['groups'] != $order['groups']) {
                            $this->result([], 1, '订单分组不可变更，如需变更取消并重新下单');
                        }
                        if ($order['mconfirm'] != 1) {
                            $this->result([], 1, '管理已确认,任务不可编辑');
                        }
                    }
                    $save = [];
                    $update = [];
                    $data['alllist'] = [];
                    $data['wllist'] = $data['wllist'] ?? [];
                    $data['zplist'] = $data['zplist'] ?? [];
                    $data['alllist'] = array_merge($data['wllist'], $data['zplist']);
                    if (count($data['alllist']) < 1) {
                        $this->result([], 1, '必须选择物料、赠品信息');
                    }
                    $getsandu = $this->getwuliaoarr($data);
                    if (!empty($getsandu['save'])) {
                        $save = $getsandu['save'];
                    }
                    if (!empty($getsandu['update'])) {
                        $update = $getsandu['update'];
                    }
                    Db::startTrans();
                    try {
                        if (!empty($data['id'])) {
                            $model->allowfield(true)->save($data, ['id' => $data['id']]);
                        } else {
                            $data['suid'] = $this->request->user_id;
                            $data['user_id'] = $this->request->user_id;
                            // $data['afconfirm'] = 1; //售后确认
                            $data['mconfirm'] = 1; //管理确认
                            $data['wconfirm'] = 1; //仓库确认
                            $data['fconfirm'] = 1; //财务确认
                            $data['id'] = $model->strict(false)->insertGetId($data);
                            foreach ($save as $k => $sv) {
                                $save[$k]['orderid'] = $data['id'];
                            }
                            (new Message())->allowfield(true)->save([
                                'orderid' => $data['id'],
                                'user_id' => $this->request->user_id,
                                'type' => $data['type'],
                                'groups' => $data['groups'] ?? 99,
                                'text' => $this->request->user['account'] . '新建了任务待确认',
                                'mconfirm' => 1
                            ]);
                        }
                        if (count($save) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($save);
                        }
                        if (count($update) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($update);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result(['id' => ($data['id'] ?? 0)], 0, '操作成功');
                    break;
                case '3':
                    $validate = new Validate([
                        // 'topid' => 'require|gt:0',
                        'nowtime' => 'require',
                        'groups' => 'require|gt:0',
                        'name' => 'require',
                        'mobile' => 'require',
                        'kremark' => 'require',
                    ], [
                        // 'topid.require' => '关联交接单必须填写',
                        // 'topid.gt' => '关联交接单必须填写',
                        'nowtime.require' => '发布时间必须填写',
                        'groups.require' => '组别不能为空',
                        'groups.gt' => '组别必须选择',
                        'mobile.require' => '联系电话不能为空',
                        'name.require' => '联系人不能为空',
                        'kremark.require' => '重点备注不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    if (mb_substr($data['name'], -1, 1, 'utf-8') == '总') {
                        $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总等泛词');
                    }
                    if (strpos($data['name'], '总监') > 0 || strpos($data['name'], '先生') > 0 || strpos($data['name'], '美女') > 0 || strpos($data['name'], '女士') > 0 || strpos($data['name'], '老板') > 0 || strpos($data['name'], '小姐') > 0) {
                        $this->result([], 1, '请填写用户具体姓名，不要填写先生、老板、小姐、美女、女士、总、总监等泛词');
                    }
                    $model = new Order();
                    //不可变更分组
                    if (!empty($data['id'])) {
                        $order = $model->where(['id' =>  $data['id'], 'type' => $data['type']])->find();
                        if (empty($order)) {
                            $this->result([], 1, '订单不存在');
                        }
                        if ($data['groups'] != $order['groups']) {
                            $this->result([], 1, '订单分组不可变更，如需变更取消并重新下单');
                        }
                        if ($order['mconfirm'] != 1) {
                            $this->result([], 1, '管理已确认,任务不可编辑');
                        }
                    }
                    $save = [];
                    $update = [];
                    $data['alllist'] = [];
                    $data['wllist'] = $data['wllist'] ?? [];
                    $data['zplist'] = $data['zplist'] ?? [];
                    $data['alllist'] = array_merge($data['wllist'], $data['zplist']);
                    if (count($data['alllist']) < 1) {
                        $this->result([], 1, '必须选择物料、赠品信息');
                    }
                    $getsandu = $this->getwuliaoarr($data);
                    if (!empty($getsandu['save'])) {
                        $save = $getsandu['save'];
                    }
                    if (!empty($getsandu['update'])) {
                        $update = $getsandu['update'];
                    }
                    Db::startTrans();
                    try {
                        if (!empty($data['id'])) {
                            $model->allowfield(true)->save($data, ['id' => $data['id']]);
                        } else {
                            $data['user_id'] = $this->request->user_id;
                            // $data['afconfirm'] = 1; //售后确认
                            $data['mconfirm'] = 1; //管理确认
                            $data['wconfirm'] = 1; //仓库确认
                            $data['fconfirm'] = 1; //财务确认
                            $data['id'] = $model->strict(false)->insertGetId($data);
                            foreach ($save as $k => $sv) {
                                $save[$k]['orderid'] = $data['id'];
                            }
                            (new Message())->allowfield(true)->save([
                                'orderid' => $data['id'],
                                'user_id' => $this->request->user_id,
                                'type' => $data['type'],
                                'groups' => $data['groups'] ?? 99,
                                'text' => $this->request->user['account'] . '新建了任务待确认',
                                'mconfirm' => 1
                            ]);
                        }
                        if (count($save) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($save);
                        }
                        if (count($update) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($update);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result(['id' => ($data['id'] ?? 0)], 0, '操作成功');
                    break;
                case '4':
                    $validate = new Validate([
                        'nowtime' => 'require',
                        'groups' => 'require|gt:0',
                        'total' => 'require|gt:0',
                        'kremark' => 'require',
                    ], [
                        'nowtime.require' => '发布时间必须填写',
                        'groups.require' => '组别不能为空',
                        'groups.gt' => '组别必须选择',
                        'total.require' => '进货金额不能为空',
                        'total.require' => '进货金额必须大于0',
                        'kremark.require' => '重点备注不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    $model = new Order();
                    //不可变更分组
                    if (!empty($data['id'])) {
                        $order = $model->where(['id' =>  $data['id'], 'type' => $data['type']])->find();
                        if (empty($order)) {
                            $this->result([], 1, '订单不存在');
                        }
                        if ($data['groups'] != $order['groups']) {
                            $this->result([], 1, '订单分组不可变更，如需变更取消并重新下单');
                        }
                        if ($order['mconfirm'] != 1) {
                            $this->result([], 1, '管理已确认,任务不可编辑');
                        }
                    }
                    $save = [];
                    $update = [];
                    $data['alllist'] = [];
                    $data['wllist'] = $data['wllist'] ?? [];
                    $data['zplist'] = $data['zplist'] ?? [];
                    $data['alllist'] = array_merge($data['wllist'], $data['zplist']);
                    if (count($data['alllist']) < 1) {
                        $this->result([], 1, '必须选择物料、赠品信息');
                    }
                    $getsandu = $this->getwuliaoarr($data);
                    if (!empty($getsandu['save'])) {
                        $save = $getsandu['save'];
                    }
                    if (!empty($getsandu['update'])) {
                        $update = $getsandu['update'];
                    }
                    Db::startTrans();
                    try {
                        if (!empty($data['id'])) {
                            $model->allowfield(true)->save($data, ['id' => $data['id']]);
                        } else {
                            $data['user_id'] = $this->request->user_id;
                            $data['mconfirm'] = 1; //王总确认
                            $data['wconfirm'] = 1; //仓库确认
                            $data['id'] = $model->strict(false)->insertGetId($data);
                            foreach ($save as $k => $sv) {
                                $save[$k]['orderid'] = $data['id'];
                            }
                            (new Message())->allowfield(true)->save([
                                'orderid' => $data['id'],
                                'user_id' => $this->request->user_id,
                                'type' => $data['type'],
                                'groups' => $data['groups'] ?? 99,
                                'text' => $this->request->user['account'] . '新建了任务待确认',
                                'mconfirm' => 1
                            ]);
                        }
                        if (count($save) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($save);
                        }
                        if (count($update) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($update);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '5':
                    $validate = new Validate([
                        'nowtime' => 'require',
                        'groups' => 'require|gt:0',
                        'total' => 'require|gt:0',
                        'kremark' => 'require',
                    ], [
                        'nowtime.require' => '发布时间必须填写',
                        'groups.require' => '组别不能为空',
                        'groups.gt' => '组别必须选择',
                        'total.require' => '进货金额不能为空',
                        'total.require' => '进货金额必须大于0',
                        'kremark.require' => '重点备注不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    $model = new Order();
                    //不可变更分组
                    if (!empty($data['id'])) {
                        $order = $model->where(['id' =>  $data['id'], 'type' => $data['type']])->find();
                        if (empty($order)) {
                            $this->result([], 1, '订单不存在');
                        }
                        if ($data['groups'] != $order['groups']) {
                            $this->result([], 1, '订单分组不可变更，如需变更取消并重新下单');
                        }
                        if ($order['mconfirm'] != 1) {
                            $this->result([], 1, '管理已确认,任务不可编辑');
                        }
                    }
                    $save = [];
                    $update = [];
                    $data['alllist'] = [];
                    $data['wllist'] = $data['wllist'] ?? [];
                    $data['zplist'] = $data['zplist'] ?? [];
                    $data['alllist'] = array_merge($data['wllist'], $data['zplist']);
                    if (count($data['alllist']) < 1) {
                        $this->result([], 1, '必须选择物料、赠品信息');
                    }
                    $getsandu = $this->getwuliaoarr($data);
                    if (!empty($getsandu['save'])) {
                        $save = $getsandu['save'];
                    }
                    if (!empty($getsandu['update'])) {
                        $update = $getsandu['update'];
                    }
                    Db::startTrans();
                    try {
                        if (!empty($data['id'])) {
                            $model->allowfield(true)->save($data, ['id' => $data['id']]);
                        } else {
                            $data['user_id'] = $this->request->user_id;
                            $data['mconfirm'] = 1; //王总确认
                            $data['wconfirm'] = 1; //仓库确认                            
                            $data['id'] = $model->strict(false)->insertGetId($data);
                            foreach ($save as $k => $sv) {
                                $save[$k]['orderid'] = $data['id'];
                            }
                            (new Message())->allowfield(true)->save([
                                'orderid' => $data['id'],
                                'user_id' => $this->request->user_id,
                                'type' => $data['type'],
                                'groups' => $data['groups'] ?? 99,
                                'text' => $this->request->user['account'] . '新建了任务待确认',
                                'mconfirm' => 1
                            ]);
                        }
                        if (count($save) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($save);
                        }
                        if (count($update) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($update);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                case '6':
                    $validate = new Validate([
                        'nowtime' => 'require',
                        'total' => 'require|gt:0',
                        'kremark' => 'require',
                    ], [
                        'nowtime.require' => '发布时间必须填写',
                        'total.require' => '采购金额不能为空',
                        'total.require' => '采购金额必须大于0',
                        'kremark.require' => '重点备注不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    $data['groups'] = 0;
                    $model = new Order();
                    //不可变更分组
                    if (!empty($data['id'])) {
                        $order = $model->where(['id' =>  $data['id'], 'type' => $data['type']])->find();
                        if (empty($order)) {
                            $this->result([], 1, '订单不存在');
                        }
                        if ($order['swconfirm'] != 1) {
                            $this->result([], 1, '管理已确认,任务不可编辑');
                        }
                    }
                    $save = [];
                    $update = [];
                    $data['alllist'] = [];
                    $data['wllist'] = $data['wllist'] ?? [];
                    $data['zplist'] = $data['zplist'] ?? [];
                    $data['alllist'] = array_merge($data['wllist'], $data['zplist']);
                    if (count($data['alllist']) < 1) {
                        $this->result([], 1, '必须选择物料、赠品信息');
                    }
                    $getsandu = $this->getwuliaoarr($data);
                    if (!empty($getsandu['save'])) {
                        $save = $getsandu['save'];
                    }
                    if (!empty($getsandu['update'])) {
                        $update = $getsandu['update'];
                    }
                    Db::startTrans();
                    try {
                        if (!empty($data['id'])) {
                            $model->allowfield(true)->save($data, ['id' => $data['id']]);
                        } else {
                            $data['user_id'] = $this->request->user_id;
                            $data['swconfirm'] = 1; //夏总确认
                            $data['wconfirm'] = 1; //仓库确认                            
                            $data['id'] = $model->strict(false)->insertGetId($data);
                            foreach ($save as $k => $sv) {
                                $save[$k]['orderid'] = $data['id'];
                            }
                            if (empty($data['groups'])) {
                                $data['groups'] = 99;
                            }
                            (new Message())->allowfield(true)->save([
                                'orderid' => $data['id'],
                                'user_id' => $this->request->user_id,
                                'type' => $data['type'],
                                'groups' => $data['groups'] ?? 99,
                                'text' => $this->request->user['account'] . '新建了任务待确认',
                                'swconfirm' => 1
                            ]);
                        }
                        if (count($save) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($save);
                        }
                        if (count($update) > 0) {
                            (new Ordergoods())->allowfield(true)->saveAll($update);
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                    break;
                default:
                    $this->result([], 1, '提交类型错误');
                    break;
            }
        } else {
            $id = $this->request->get('id/d', 0);
            $type = $this->request->get('type/d', 0);
            if (empty($type)) {
                $result = (new Order())->where(['id' => $id])->find();
            } else {
                $result = (new Order())->where(['id' => $id, 'type' => $type])->find();
            }
            if ($result) {
                $result['images'] = json_decode($result['images'], true) ?? [];
                $result['areas'] = (float)$result['areas'];
                $result['total'] = (float)$result['total'];
                $result['groups'] = (string)$result['groups'];
                $result['groups_name'] =  config()["config"]['type_name'][$result['groups']] ?? '';
                $result['goods'] = (new Ordergoods())
                    ->field('id as delid,goodsid as id,title as name,number,fhr,isfahuo')
                    ->where(['orderid' => $result['id'], 'del' => 1, 'type' => [1, 2]])
                    ->select() ?? [];
                $result['zpgoods'] = (new Ordergoods())
                    ->field('id as delid,goodsid as id,title as name,number,sjtotal as total')
                    ->where(['orderid' => $result['id'], 'del' => 1, 'type' => 3])
                    ->select() ?? [];
                if ($result['suid'] > 0) {
                    $result['uidname'] = (new Users())->where('id', $result['suid'])->value('account');
                }
            } else {
                $result['goods'] = [];
            }
            $this->result($result, 0, '获取成功');
        }
    }

    //获取要保存的物料数据
    public function  getwuliaoarr($data)
    {
        $save = [];
        $update = [];
        foreach ($data['alllist'] as $wlist) {
            if (empty($wlist['id'])) {
                $this->result([], 1, $wlist['name'] . '物料数据错误，请删除重填');
            }
            if (empty($wlist['number'])) {
                $this->result([], 1, '物料数量不能低于1');
            }
            //查找物料数据
            $goods = (new Goods())->where(['id' => $wlist['id']])->find();
            if (empty($goods)) {
                $this->result([], 1, '[' . $wlist['name'] . ']系统已不存在');
            }
            if (($goods['type'] == 1 || $goods['type'] == 2) && $goods['groups'] != $data['groups']) {
                $this->result([], 1, '[' . $wlist['name'] . ']分组不匹配');
            }
            if ($goods['type'] == 3 && $goods['groups'] != 0) {
                $this->result([], 1, '[' . $wlist['name'] . ']分组不匹配');
            }
            if ($goods['type'] == 3 && empty($wlist['total']) && $data['type'] != 6) {
                $this->result([], 1, '[' . $wlist['name'] . ']价格不能为0');
            }
            //匹配仓位
            if ($goods['type'] == 3) {
                if (in_array($data['groups'], [7, 8]) && $goods['cangku'] != 2) {
                    $this->result([], 1, '郑州项目赠品请选择郑州仓位');
                } elseif (!in_array($data['groups'], [7, 8]) && $goods['cangku'] != 1) {
                    $this->result([], 1, '长沙项目赠品请选择长沙仓位');
                }
            }
            //更新物料信息
            if (empty($wlist['delid'])) {
                $save[] = [
                    'orderid' => $data['id'] ?? 0,
                    'goodsid' => $goods['id'],
                    'groups' => $goods['groups'],
                    'type' => $goods['type'],
                    'title' => $goods['title'],
                    'number' => $wlist['number'],
                    'total' => $goods['total'],
                    'sjtotal' => $wlist['total'] ?? 0,
                    'del' => 1
                ];
            } else {
                $ordergoods = (new Ordergoods())->where(['id' => $wlist['delid']])->find();
                if (empty($ordergoods)) {
                    $save[] = [
                        'orderid' =>  $data['id'] ?? 0,
                        'goodsid' => $goods['id'],
                        'groups' => $goods['groups'],
                        'type' => $goods['type'],
                        'title' => $goods['title'],
                        'number' => $wlist['number'],
                        'total' => $goods['total'],
                        'sjtotal' => $wlist['total'] ?? 0,
                        'del' => 1
                    ];
                } else {
                    $update[] = [
                        'id' => $wlist['delid'],
                        'goodsid' => $goods['id'],
                        'orderid' =>  $data['id'] ?? 0,
                        'groups' => $data['groups'],
                        'type' => $goods['type'],
                        'title' => $goods['title'],
                        'number' => $wlist['number'],
                        'total' => $goods['total'],
                        'sjtotal' => $wlist['total'] ?? 0,
                        'del' => 1
                    ];
                }
            }
        }
        $return = [
            'save' => $save,
            'update' => $update
        ];
        return $return;
    }

    public function getconfig()
    {
        $result = [
            'group' => [], //分组
            'orderuser' => [], //交接单客户
            'shouhou' => [], //售后
        ];
        $havegroup = explode(',', $this->request->user['groups']);
        //项目组
        $group = config()["config"]['type'] ?? [];
        foreach ($group as $k => $v) {
            if ($this->request->user['groups'] != 99) {
                if (in_array($k, $havegroup)) {
                    $result['group'][] = [
                        'id' => (string)$k,
                        'name' => $v
                    ];
                }
            } else {
                $result['group'][] = [
                    'id' => (string)$k,
                    'name' => $v
                ];
            }
        }
        $groups = [];
        foreach ($result['group'] as $group) {
            $groups[] = $group['id'];
        }
        $orderuser = (new Order())->field('id,groups,name,mobile')->where(['groups' => $groups])->where(['del' => 1, 'type' => 1, 'status' => [1, 2]])->select();
        foreach ($orderuser as $user) {
            $groups_type = config()["config"]['type_name'][$user['groups']];
            $result['orderuser'][] = [
                'value' => (string)$user['id'],
                'label' => $user['name'] . '(' . $user['mobile'] . ')[' . $groups_type . ']',
                'extra' => ['name' => $user['name'], 'mobile' => $user['mobile'], 'id' => $user['id'], 'groups' => (string)$user['groups']]
            ];
        }
        $shouhou = (new Users())->field('id,account,groups')->where(['del' => 1, 'type' => 2])->select() ?? [];
        foreach ($shouhou as $user) {
            if ($user['groups'] == 99) {
                $result['shouhou'][] = [
                    'value' => (string)$user['id'],
                    'label' => $user['account']
                ];
            } else {
                $sgroupsgive = explode(',', $user['groups']);
                $havjs = array_intersect($groups, $sgroupsgive);
                if (count($havjs) > 0) {
                    $result['shouhou'][] = [
                        'value' => (string)$user['id'],
                        'label' => $user['account']
                    ];
                }
            }
        }
        $this->result($result, 0, '获取成功');
    }

    public function login()
    {
        $data = $this->request->post();
        $type = $this->request->post('type/d', 1); //1手机号登录  2微信授权
        if ($type == 1) {
            $validate = new Validate([
                'mobile' => 'require',
                'password' => 'require',
            ], [
                'mobile.require' => '登陆账号不能为空',
                'password.require' => '登陆密码不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $model = new Users();
            //判断用户是否已经注册
            $user = $model->where('account', $data['mobile'])->find();
            if (empty($user)) {
                $this->result([], 1, '账号不存在');
            }
            if ($user['password'] != md5(md5($data['password']))) {
                $this->result([], 1, '账号密码错误');
            }
            $token = 'user_' . md5(time() . $user['account']);
            Redis::setex($token, 30 * 86400, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        } else {
            $this->result([], 1, '暂未开放此登录方式');
        }
        $this->result([], 1, '登录失败');
    }

    public function info()
    {
        $result = (new Users())->field('password,created,del', true)->where('id', $this->request->user_id)->find();
        $row = [];
        if ($result) {
            if ($result['groups'] == 99) {
                $grouplist  = '全部项目';
            } else {
                $groups = explode(',', $result['groups']) ?? [];
                $grouplist = '';
                foreach ($groups as $group) {
                    $grouplist  = $grouplist . (config()["config"]['type_name'][$group] ?? '');
                }
            }
            if (mb_strlen($grouplist) > 8) {
                $grouplist = mb_substr($grouplist, 0, 8, "utf-8") . "等";
            }
            $row = [
                'id' => $result['id'],
                'type' =>  $result['type'],
                'name' => $result['account'],
                'images' => $result['images'] ?? 'https://whapi.dida555.com/ximages/logo.jpg',
                'type_name' => config()["config"]['groups'][$result['type']] ?? '',
                'group' => $grouplist,
                'mobile' => $result['account']
            ];
            $row['rukou1'] = 1;
            $row['rukou2'] = 1;
            $row['rukou3'] = 1;
            $row['rukou4'] = 1;
            $row['rukou5'] = 1;
            $row['rukou6'] = 1;
            $row['look'] = 1;
            //查看数据
            if ($this->request->user['type'] == 3 || $this->request->user['type'] == 4 || $this->request->user['type'] == 9 || $this->request->user['type'] == 10) {
                $row['look'] = 2;
            }
            //业务经理提交
            if ($this->request->user['type'] == 1) {
                $row['rukou1'] = 2;
            }
            //售后提交
            if ($this->request->user['type'] == 2) {
                $row['rukou2'] = 2;
                $row['rukou3'] = 2;
            }
            //财务提交
            if ($this->request->user['type'] == 3) {
                $row['rukou4'] = 2;
                $row['rukou5'] = 2;
            }
            //采购提交
            if ($this->request->user['type'] == 5) {
                $row['rukou6'] = 2;
            }
            $row['iscode'] = 1; //未授权
            $row['qrcode'] = '';
            $row['gzhs'] = 'https://dtapis.dida555.com/neqrcode.jpg';
            if (!empty($this->request->user['openid'])) {
                $row['iscode'] = 2; //已授权
            }
            try {
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . config('wechat2.')['app_id'] . "&redirect_uri=https://"
                    . Env('APP_API_URL')
                    . "/user/getopenid?userid=" . $row['id'] . '&state=1&response_type=code&scope=snsapi_base#wechat_redirect';
                $savePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/qrcode/';
                $qrLevel = 'H';
                $qrSize = '8';
                if ($filename = createQRcode($savePath, $url, $qrLevel, $qrSize)) {
                    $qcode = url('/uploads/qrcode/' . $filename, '', '', true);
                    $row['qrcode'] = $qcode;
                }
            } catch (\Exception $e) {
                dump($e->getMessage());
            }
        }
        $this->result($row, 0, '获取成功');
    }

    public function getothers()
    {
        $name = $this->request->get('name/s', '');
        $config = (new Config())->where('name', $name)->find();
        $this->result($config, 0, '获取成功');
    }

    public function getopenid()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'userid' => 'require',
            'code' => 'require'
        ], [
            'userid.require' => '账号不能为空',
            'code.require' => 'code必须填写',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $users = (new Users())->where('id', $data['userid'])->find();
        if (empty($users)) {
            $results = ['status' => 1, 'info' => '授权失败,用户不存在'];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $result = $app->oauth->user();
            $user = $app->user->get($result['id']);
            if (empty($user['subscribe']) || $user['subscribe'] != 1) {
                return view(null, ['list' => ['status' => 1, 'info' => '授权前请先关注[东之晟]公众号!']]);
            }
            if ($users['openid'] == $result['id']) {
                $res = true;
            } else {
                $res = (new Users())->where('id', $users['id'])->update(['openid' => $result['id']]);
            }
            if (!$res) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            $results = ['status' => 0, 'info' => '账号【' . $users['account'] . '】授权成功，已订阅公众号订单通知服务!'];
            return view(null, ['list' => $results]);
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => $e->getMessage()];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 1, 'info' => '授权失败,请重试'];
        return view(null, ['list' => $results]);
    }

    public function addressjson()
    {
        $json_data = file_get_contents('address.json'); // 读取json文件中的数据
        $data = json_decode($json_data, true) ?? []; // 将json数据转换为PHP数组
        return json($data);
    }
}
